﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BackupsDatabase
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        String defPath = @"D:\DaoZe\Backups\";
        string host = "127.0.0.1";
        string user = "root";
        string password = "admin";
        string database = "--all-databases";
       


       
        protected override void OnStart(string[] args)
        {
            ;
           if (!Directory.Exists(defPath))//判断文件目录是否存在
            {
                Directory.CreateDirectory(defPath);//创建文件目录
            }

            Thread thread = new Thread(BackupAction);
            thread.Start();
            
        }


        protected override void OnStop()
        {
           
        }


        private DateTime? lastBackupDateTime=null;
        private void BackupAction()
        {
          
            while (true)
            {
                if (lastBackupDateTime==null)
                {
                    lastBackupDateTime = DateTime.Now;
                }
                else
                {
                    DateTime last = (DateTime)lastBackupDateTime;
                    if (last.Hour!= DateTime.Now.Hour)
                    {
                        string backupFile = defPath + DateTime.Now.ToString("yyyyMMddHH") + ".sql";
                        String backupDatabaseStr = String.Format("mysqldump -h{0} -u{1} -p{2} {3} > {4} ", host, user, password, database, backupFile);

                        Cmd cmd = new Cmd();
                        cmd.RunCmd(backupDatabaseStr);
                        lastBackupDateTime = DateTime.Now;
                    }
                }
                
              
              
            }
            
        }
    }
}
